import {
  $authorization,
  $callList,
  $giftAnim,
  $inviteConfirm,
  $loading,
  $message,
  $redPackets,
  $scorllMessage,
  $signinValiation,
  $tips
} from "@/utils/components-proxy";
import { PageOptions, data, page } from "@/library/lib";
import { using } from "@/library/injector";
import { $errTip } from "@/utils/error-handler";
import { AD } from "@/ad";
import { Time } from "@/utils/time";
import { delayTask, random } from "@/utils/utils";
import { MiniService } from "../../services/MiniService";
import { TokenFactory } from "@/services/TokenFactory";



/**
 * Page - index
 * @create 2020-07-10 00:00:00
 * @author Halo
 *
 */

@page
export default class extends PageOptions {
  @using("MiniService") miniService: MiniService;
  @data enable: Boolean = true;
  @data user: any = null;
  @data anchor: any = null;
  /* 页面加载回调 */
  async onLoad(query: Record<string, string | undefined>) {

  }
  async onShow() {
    this.getMiniConfig()
    await delayTask(() => TokenFactory.accessToken, 1000, 20);
    this.getUserConfig()
  }
  async onHide() {
  }
  onUnload() {
  }
  onShareAppMessage(res: any): WechatMiniprogram.Page.ICustomShareContent {
    return {
      title: "title",
      path: "/pages/index/index",
    };
  }
  /**
   * 当前用户信息
   */
  async getUserConfig() {
    this.miniService.getUserConfig().then(user => {
      this.setData({
        user
      })
    })
  }

  async getMiniConfig() {
    this.miniService.getMiniConfig().then(data => {
      console.log(data)
      let { anchor, wxMiniAdConfigs, wxMiniConfigImageUrls } = data
      this.setData({
        anchor: anchor
      })
      wxMiniConfigImageUrls = wxMiniConfigImageUrls ? JSON.stringify(wxMiniConfigImageUrls) : ""
      // anchor = anchor ? JSON.stringify(anchor) : ""
      wx.setStorageSync("anchor", anchor)
      wx.setStorageSync("wxMiniConfigImageUrls", wxMiniConfigImageUrls)
    })
  }

  /**
 * 播放广告
 */
  async ad() {
    // 播放广告
    if (!this.data.enable) return $scorllMessage.msg(`您点击过快,请稍后后重试!`);
    this.data.enable = false
    setTimeout(() => {
      this.data.enable = true
    }, 5000);
    let startTime = Time.now;
    AD.invoke.video(isEnded => this.onAdPlayed(isEnded, startTime));
  }
  /**
 * 广告关闭
 */
  async onAdPlayed(isEnded: boolean, startTime: number) {
    let playTime = Time.now - startTime;
    console.log(playTime)
    if (playTime > 10000) {
      this.miniService.AdSubmit(isEnded).then(user => {
        console.log(user)
        this.setData({
          user
        })
      })
      if (isEnded) {
        $message.msg({
          title: "恭喜你",
          content: "获得一颗❤"
        })
      } else {
        $message.msg({
          title: "提示",
          content: "您没有看完广告,无法获得奖励"
        })
      }
    }

  }
  /**
   * 跳转
   */
  support() {
    wx.navigateTo({
      url: "/pages/detail/detail"
    })
  }
}
